<?php

namespace core;

class Controller
{
    public $middlewares = [];
    public function __construct(string $method, array $middlewares, Request $request, Response $response) {
        $this->applyMiddleware(array_merge($this->middlewares, $middlewares), $method, $request, $response);
    }

    private function applyMiddleware(array $middlewares, string $method, Request $request, Response $response): void {
        if (!empty($middlewares)) {
            $middleware = array_shift($middlewares);
            $next = function () use ($middlewares, $method, $request, $response) {
                $this->applyMiddleware($middlewares, $method, $request, $response);
            };
            call_user_func_array([new $middleware(), 'handle'], [$request, $response, $next]);
        } else {
            $this->{$method}($request, $response);
        }
    }
}
